package com.yn.bigevent.controller;

import com.yn.bigevent.pojo.Category;
import com.yn.bigevent.pojo.Result;
import com.yn.bigevent.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    //增加文章分类
    @PostMapping
    public Result add(@RequestBody @Validated(Category.Add.class) Category category){
        categoryService.add(category);
        return Result.success();
    }

    //列表查询
    @GetMapping
    public Result<List<Category>> list(){
        List<Category> cs = categoryService.list();
        return Result.success(cs);
    }


    //根据分类id查询分类信息
    @GetMapping("/detail")
    public Result<Category> detail(Integer id){
        Category c=categoryService.findById(id);
        return Result.success(c);
    }

    //更新文章分类
    @PutMapping
    public Result update(@RequestBody @Validated(Category.Update.class) Category category){
        categoryService.update(category);
        return Result.success();
    }

    //根据分类id删除文章分类
    @DeleteMapping
    public Result delete(Integer id){
        //id是分类id
        //先查询该分类是否存在，存在删除，不存在error
        Category c = categoryService.findById(id);//根据分类id查分类
        if(c==null){
            return Result.error("该分类不存在");
        }
        categoryService.delete(id);
        return Result.success();
    }
}
